<template>
    <header id="header" v-if="loggedIn && !notFound" :class="(($route.meta.componentName == 'SGCluster') && ((!$route.name.includes('Create') && (!$route.name.includes('Edit')) && ($route.name != 'ClusterOverview')))? 'clusterHeader' : '')">
        <ul class="breadcrumbs" v-if="!['SGConfig', 'User', 'Role', 'ClusterRole'].includes($route.meta.componentName)">

            <!--Namespace-->
            <li class="namespace" v-if="$route.name.includes('GlobalDashboard') || $route.params.hasOwnProperty('namespace')">
                <template v-if="$route.name.includes('GlobalDashboard')">
                    Namespaces Overview
                </template>
                <template v-else>
                    <svg xmlns="http://www.w3.org/2000/svg" width="20.026" height="27"><g fill="#00adb5"><path d="M1.513.9l-1.5 13a.972.972 0 001 1.1h18a.972.972 0 001-1.1l-1.5-13a1.063 1.063 0 00-1-.9h-15a1.063 1.063 0 00-1 .9zm.6 11.5l.9-8c0-.2.3-.4.5-.4h12.9a.458.458 0 01.5.4l.9 8a.56.56 0 01-.5.6h-14.7a.56.56 0 01-.5-.6zM1.113 17.9a1.063 1.063 0 011-.9h15.8a1.063 1.063 0 011 .9.972.972 0 01-1 1.1h-15.8a1.028 1.028 0 01-1-1.1zM3.113 23h13.8a.972.972 0 001-1.1 1.063 1.063 0 00-1-.9h-13.8a1.063 1.063 0 00-1 .9 1.028 1.028 0 001 1.1zM3.113 25.9a1.063 1.063 0 011-.9h11.8a1.063 1.063 0 011 .9.972.972 0 01-1 1.1h-11.8a1.028 1.028 0 01-1-1.1z"/></g></svg>
                    <template v-if="$route.name == 'NamespaceOverview'">
                        {{ currentPath.namespace }}
                    </template>
                    <template v-else>
                        <router-link :to="'/' + currentPath.namespace" title="Namespace Overview">
                            {{ currentPath.namespace }}
                        </router-link>
                    </template>
                </template>
            </li>

            <template v-if="!notFound && !$route.params.hasOwnProperty('namespace') && iCan('create', 'namespaces') && ($route.name !== 'CreateNamespace')">
                <router-link to="/namespaces/new" class="floatRight add" data-field="CreateNamespace">
                    Create Namespace
                </router-link>
            </template>
            <template v-else-if="$route.name === 'CreateNamespace'">
                Namespaces
            </template>

            <template v-if="$route.params.hasOwnProperty('namespace') && $route.meta.hasOwnProperty('componentName')">
                <!--Kind-->
                <template v-if="!['NamespaceOverview', 'GlobalDashboard'].includes($route.name)">
                    <li>
                        <span class="component" :class="$route.meta.componentName.toLowerCase()"></span>

                        <template v-if="($route.meta.componentName !== 'SGConfig') && (currentPath.name || $route.name.startsWith('Create') || $route.params.hasOwnProperty('backupname'))">
                            <template v-if="( ( (kind === 'users') && havePermissionsTo.get.users ) || (kind === 'sgstreams') || iCan('list', kind, $route.params.namespace))">
                                <router-link :to="'/' + currentPath.namespace + '/' + kind" :title="$route.meta.componentName + 's'">
                                    {{ $route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName + 's' : $route.meta.componentName + 's' }}
                                </router-link>
                            </template>
                            <template v-else>
                                {{ $route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName + 's' : $route.meta.componentName + 's' }}
                            </template>
                        </template>
                        <template v-else>
                            {{ $route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName + 's' : $route.meta.componentName + 's' }}
                        </template>
                    </li>
                </template>
                
                <!--CRD Name-->
                <template v-if="currentPath.hasOwnProperty('name') && currentPath.name.length">
                    <li>
                        <template v-if="(currentPath.component.startsWith('Edit')) || ($route.meta.componentName == 'SGCluster') || ($route.meta.componentName == 'SGShardedCluster')">
                            <router-link :to="'/' + currentPath.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + currentPath.name" :title="currentPath.name">
                                {{ currentPath.name }}
                            </router-link>
                        </template>
                        <template v-else>
                            <span>{{ currentPath.name }}</span>
                        </template>
                    </li>
                </template>

                <!--Cluster name on Backups Tab-->
                <template v-if="$route.params.hasOwnProperty('name') && !currentPath.name">
                    <li>
                        <template v-if="currentPath.component.startsWith('Edit') || $route.name == 'CreateClusterBackup'">
                            <router-link :to="'/' + currentPath.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name" :title="$route.params.name">
                                {{ $route.params.name }}
                            </router-link>
                        </template>
                        <template v-else>
                            <span>{{ $route.params.name }}</span>
                        </template>
                    </li>
                </template>

                <!--Cluster Tabs-->
                <template v-if="['SGCluster', 'SGShardedCluster'].includes($route.meta.componentName) && !['ClusterOverview', 'EditCluster', 'CreateCluster', 'ShardedClusterOverview', 'EditShardedCluster', 'CreateShardedCluster'].includes($route.name)">
                    <li class="back">
                        <template v-if="$route.name.includes('Backup') && $route.name != 'ClusterBackups'">
                            <router-link :to="'/' + currentPath.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + ($route.params.hasOwnProperty('name') ? $route.params.name : currentPath.name) + '/sgbackups'" title="Backups">
                                Backups
                            </router-link>
                        </template>

                        <template v-else>
                            <span>
                                <template v-if="$route.name.endsWith('Status')">Status</template>
                                <template v-else-if="$route.name.endsWith('Info') || $route.name.endsWith('Config')">Configuration</template>
                                <template v-else-if="$route.name.includes('Backup')">Backups</template>
                                <template v-else-if="$route.name.endsWith('Logs')">Logs</template>
                                <template v-else-if="$route.name.includes('Monitor')">Monitoring</template>
                                <template v-else-if="$route.name.includes('Events')">Events</template>
                            </span>
                        </template>
                    </li>
                </template>

                <!--Backup Name-->
                <template v-if="$route.params.hasOwnProperty('backupname')">
                    <li>
                        <template v-if="currentPath.component.startsWith('Edit')">
                            <template v-if="$route.params.hasOwnProperty('name')">
                                <router-link :to="'/' + currentPath.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/sgbackup/' + $route.params.backupname" :title="$route.params.backupname">
                                    {{ $route.params.backupname }}
                                </router-link>
                            </template>

                            <template v-else>
                                <router-link :to="'/' + currentPath.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.backupname" :title="$route.params.backupname">
                                    {{ $route.params.backupname }}
                                </router-link>
                            </template>   
                        </template>
                        
                        <template v-else>
                            <span>{{ $route.params.backupname }}</span>
                        </template>
                    </li>
                </template>

                <!--Create / Edit-->
                <template v-if="currentPath.component.startsWith('Edit') || currentPath.component.startsWith('Create')">
                    <li>
                        <template v-if="currentPath.component.startsWith('Edit')">
                            <span>Edit</span>
                        </template>
                        <template v-else>
                            <span>Create</span>
                        </template>
                    </li>
                </template>

                <!--Babelfish Compass-->
                <template v-if="$route.meta.componentName == 'Application'">
                    <li>
                        <span>Babelfish Compass</span>
                    </li>
                </template>
            </template>
        </ul>

        <template v-if="$route.params.hasOwnProperty('namespace') && $route.meta.hasOwnProperty('componentName')">
            <div class="actions" v-if="!['User', 'Role', 'ClusterRole'].includes($route.meta.componentName)">
                <!--Docs Links-->
                <template v-if="currentPath.component == 'BabelfishCompass'">
                    <a class="documentation" href="https://github.com/babelfish-for-postgresql/babelfish_compass/" target="_blank" title="Babelfish Compass Documentation">Babelfish Compass Documentation</a>
                </template>
                <template v-else-if="($route.meta.componentName == 'SGDistributedLog') || ($route.meta.componentName == 'SGDbOp')">
                    <a class="documentation" :href="'https://stackgres.io/doc/latest/reference/crd/' + $route.meta.componentName.toLowerCase() + 's'" target="_blank" :title="$route.meta.componentName + 's Documentation'">{{ $route.meta.componentName }}s Documentation</a>
                </template>
                <template v-else-if="$route.params.hasOwnProperty('namespace') && (kind !== 'users')">
                    <a class="documentation" :href="'https://stackgres.io/doc/latest/reference/crd/' + ($route.meta.customComponentName == 'SGPoolingConfig' ? $route.meta.customComponentName.toLowerCase() : $route.meta.componentName.toLowerCase())" target="_blank" :title="$route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName + ' Documentation': $route.meta.componentName + ' Documentation'">{{ $route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName : $route.meta.componentName }} Documentation</a>
                </template>

                <!--Actions-->
                <div class="crdActionLinks" v-if="!['Create', 'Edit'].includes($route.name)">
                    <template v-if="!$route.params.hasOwnProperty('name') && !$route.params.hasOwnProperty('backupname') && $route.name != 'BabelfishCompass'">
                        <router-link 
                            v-if="(kind !== 'users') && iCan('create', kind, $route.params.namespace)"
                            :to="'/' + $route.params.namespace + '/' + kind + '/new'" class="add" :title="'Add New ' + getSuffix($route.meta.componentName)">
                            Add New
                        </router-link>
                    </template>
                    <template v-if="($route.params.hasOwnProperty('name') || $route.params.hasOwnProperty('backupname'))">
                        <template v-if="($route.name == 'SingleClusterBackups')">
                            <router-link v-if="iCan('patch', kind, $route.params.namespace)" :to="'/' + $route.params.namespace + '/sgcluster/' +  $route.params.name + '/sgbackup/' + $route.params.backupname + '/edit'" :title="'Edit ' + getSuffix($route.meta.componentName)" :class="$route.name.includes('Script') && isDefaultScript($route.params.name) && 'disabled'">
                                Edit
                            </router-link>
                        </template>
                        <template v-else-if="($route.name == 'SingleBackups')">
                            <router-link v-if="iCan('patch', kind, $route.params.namespace)" :to="'/' + $route.params.namespace + '/sgbackup/' + $route.params.backupname + '/edit'" :title="'Edit ' + getSuffix($route.meta.componentName)" :class="$route.name.includes('Script') && isDefaultScript($route.params.name) && 'disabled'">
                                Edit
                            </router-link>
                        </template>
                        <template v-else-if="!$route.name.includes('DbOp')">
                            <router-link v-if="( ( (kind === 'users') && havePermissionsTo.patch.users ) || iCan('patch', kind, $route.params.namespace) )" :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/edit'" :title="'Edit ' + getSuffix($route.meta.componentName)" :class="$route.name.includes('Script') && isDefaultScript($route.params.name) && 'disabled'">
                                Edit
                            </router-link>
                        </template>
                        <template v-if="!$route.name.includes('DbOp') && ($route.name != 'SingleBackups')">
                            <a v-if="( ( (kind === 'users') && havePermissionsTo.create.users ) || iCan('create', kind, $route.params.namespace) )" @click="cloneCRD((($route.meta.hasOwnProperty('customComponentName')) ? ($route.meta.customComponentName + 's') : ($route.meta.componentName + 's') ), $route.params.namespace, $route.params.name)" class="cloneCRD" :title="(($route.meta.componentName == 'SGCluster') ? ('Clone ' + getSuffix($route.meta.componentName) + ' Configuration') : ('Clone ' + getSuffix($route.meta.componentName)))">
                                Clone
                            </a>
                        </template>
                        <a v-if="( ( (kind === 'users') && havePermissionsTo.delete.users ) || iCan('delete', kind, $route.params.namespace) )" @click="deleteCRD(kind, $route.params.namespace, $route.params.name, '/' + $route.params.namespace + '/' + kind)" class="deleteCRD" :title="'Delete ' + getSuffix($route.meta.componentName)" :class="!isDeletable ? 'disabled' : ''">
                            Delete
                        </a>
                        <template v-if="$route.meta.componentName == 'SGCluster'">
                            <a @click="setRestartCluster($route.params.namespace, $route.params.name)" class="restartCluster lastItem" title="Restart Cluster">
                                Restart
                            </a>
                        </template>

                        <template v-if="
                            isStandbyCluster &&
                            ($route.meta.componentName == 'SGCluster')
                        ">
                            <a
                                class="plain lastItem"
                                @click="promoteCluster"
                                data-field="promote-sgcluster"
                            >
                                Promote
                            </a>
                        </template>

                        <router-link :to="'/' + $route.params.namespace + '/' + kind" :title="$route.meta.hasOwnProperty('customComponentName') ? 'Go to ' + $route.meta.customComponentName +'s List' : 'Go to ' + $route.meta.componentName + 's List'" class="lastItem">
                            Go to {{ $route.meta.hasOwnProperty('customComponentName') ? $route.meta.customComponentName : $route.meta.componentName }}s List
                        </router-link>
                    </template>
                </div>
            </div>
        </template>

        <!--Cluster Tabs-->
        <template v-if="['SGCluster', 'SGShardedCluster'].includes($route.meta.componentName) && !['ClusterOverview', 'ShardedClusterOverview', 'EditCluster', 'CreateCluster', 'EditShardedCluster', 'CreateShardedCluster'].includes($route.name)">
            <ul class="tabs">
                <li>
                    <router-link :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name" title="Status" class="status">Status</router-link>
                </li>
                <li>
                    <router-link :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/config'" title="Configuration" class="info">Configuration</router-link>
                </li>
                <li v-if="iCan('list','sgbackups',$route.params.namespace) && ($route.meta.componentName == 'SGCluster')" :class="$route.name.includes('Backup') && 'active'">
                    <router-link :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/sgbackups'" title="Backups" class="backups">Backups</router-link>
                </li>
                <li v-if="iCan('list','sgdistributedlogs',$route.params.namespace) && ($route.meta.componentName == 'SGCluster') && hasLogs">
                    <router-link :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/logs'" title="Distributed Logs" class="logs">Logs</router-link>
                </li>
                <li v-if="hasMonitoring" :class="$route.name.includes('Monitor') && 'active'">
                    <router-link id="grafana-btn" :to="'/' + $route.params.namespace + '/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/monitor'" title="Grafana Dashboard" class="grafana">Monitoring</router-link>
                </li>
                <li v-if="($route.meta.componentName == 'SGCluster')" :class="$route.name == 'SingleClusterEvents' && 'active'">
                    <router-link :to="'/' + $route.params.namespace +'/' + $route.meta.componentName.toLowerCase() + '/' + $route.params.name + '/events'" title="Events" class="events">Events</router-link>
                </li>
            </ul>
        </template>
    </header>
</template>

<script>
import sgApi from '../../api/sgApi';
    import store from '../../store'
	import { mixin } from '../mixins/mixin'

    export default {
        name: 'HeaderSection',

        mixins: [mixin],

        computed: {

            kind () {
                return (this.$route.meta.componentName.toLowerCase() + 's');
            },

			currentPath () {
				return store.state.currentPath
			},

			notFound () {
				return store.state.notFound
			},

            isDeletable () {
                const vc = this;
                let c = '';
                let l = '';
                let isDeletable = false;
                const kind = vc.$route.meta.componentName.toLowerCase() + 's';

                if(store.state[kind] === null) {
                    return false;
                } else {
                    switch(kind) {
                        
                        case 'sgobjectorages':
                            // Looks for a cluster that depends on this resource
                            if(store.state.sgclusters !== null) {
                                c = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && ( vc.hasProp(c, 'data.spec.configurations.backups.sgObjectStorage') &&  (c.data.spec.configurations.backups.sgObjectStorage == vc.$route.params.name)))
                                // If there is any then it can't be deleted
                                isDeletable = (typeof c == 'undefined')
                            } else {
                                isDeletable = false;
                            }
                            break;
                        case 'sgdistributedlogs':
                            if(store.state.sgclusters !== null) {
                                c = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && ((c.data.spec.hasOwnProperty('distributedLogs')) &&  (c.data.spec.distributedLogs.sgDistributedLogs == vc.$route.params.name)))
                                isDeletable = (typeof c == 'undefined')
                            } else {
                                isDeletable = false;
                            }
                            break;
                        case 'sginstanceprofiles':
                            if( (store.state.sgclusters !== null) && (store.state.sgdistributedlogs !== null)) {
                                c = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.data.spec.sgInstanceProfile == vc.$route.params.name));
                                l = store.state.sgdistributedlogs.find(l => (l.data.metadata.namespace == vc.$route.params.namespace) && (l.data.spec.sgInstanceProfile == vc.$route.params.name))
                                return ((typeof c == 'undefined') && (typeof l == 'undefined'))
                            } else {
                                isDeletable = false;
                            }
                            break;
                        case 'sgpgconfigs':
                            if( (store.state.sgclusters !== null) && (store.state.sgdistributedlogs !== null)) {
                                c = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.data.spec.configurations.sgPostgresConfig == vc.$route.params.name));
                                l = store.state.sgdistributedlogs.find(l => (l.data.metadata.namespace == vc.$route.params.namespace) && (l.data.spec.configurations.sgPostgresConfig == vc.$route.params.name))
                                return ((typeof c == 'undefined') && (typeof l == 'undefined'))
                            } else {
                                isDeletable = false;
                            }
                            break;
                        case 'sgpoolconfigs':
                            if(store.state.sgclusters !== null) {
                                c = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.data.spec.configurations.sgPoolingConfig == vc.$route.params.name))
                                isDeletable = (typeof c == 'undefined')
                            } else {
                                isDeletable = false;
                            }
                            break;
                        case 'sgscripts':
                            isDeletable = !vc.isDefaultScript(vc.$route.params.name)
                            break;
                        default:
                            if(store.state[kind] !== null) {
                                c = store.state[kind].find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.data.metadata.name == vc.$route.params.name))
                                isDeletable = (typeof c !== 'undefined')
                            } else {
                                isDeletable = false;
                            }
                            break;
                    }

                    return isDeletable;
                }
            },
            
            hasLogs () {
                if(store.state.sgclusters === null) {
                    return false;
                } else {
                    const vc = this;

                    let cluster = store.state.sgclusters.filter(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.name == vc.$route.params.name))

                    if((cluster.length > 0) && (cluster[0].data.spec.hasOwnProperty('distributedLogs')))
                        return true
                    else
                        return false
                }
            },

            hasMonitoring () {
                const vc = this;

                if(store.state[vc.kind] === null) {
                    return false;
                } else {
                    let cluster = store.state[vc.kind].find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.name == vc.$route.params.name) && c.data.hasOwnProperty('grafanaEmbedded') && c.data.grafanaEmbedded)

                    return (typeof cluster !== 'undefined');
                }
            },

            isStandbyCluster() {
                if(store.state.sgclusters === null) {
                    return false;
                } else {
                    const vc = this;

                    let cluster = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.name == vc.$route.params.name) && c.data.spec.hasOwnProperty('replicateFrom') && (c.data.spec.replicateFrom !== null))

                    return (typeof cluster !== 'undefined');
                }
            }
		}, 

        methods: {

            getSuffix(crd) {

                let suffixes = {
                    'SGCluster': 'Cluster',
                    'SGShardedCluster': 'Sharded Cluster',
					'SGInstanceProfile': 'Profile',
                    'SGPgConfig': 'Configuration',
                    'SGPoolConfig': 'Configuration',
                    'SGDistributedLog': 'Logs Server',
                    'SGBackup': 'Backup',
                    'SGDbOp': 'Operation',
                    'SGObjectStorage': 'Object Storage',
                    'SGScript': 'Script'
				}

				return suffixes[crd];
            },

            isDefaultScript(scriptName) {
                const vc = this;
                let script = (store.state.sgscripts !== null)
                    ? store.state.sgscripts.find( s => (s.data.metadata.namespace == vc.$route.params.namespace) && (s.data.metadata.name == scriptName) )
                    : undefined;

                return ( (typeof script != 'undefined') && ( script.data.status.clusters.length && (script.name == (script.data.status.clusters[0] + '-default') ) ) )
            },

            promoteCluster() {
                if(store.state.sgclusters !== null) {
                    const vc = this;

                    let cluster = store.state.sgclusters.find(c => (c.data.metadata.namespace == vc.$route.params.namespace) && (c.name == vc.$route.params.name) && c.data.spec.hasOwnProperty('replicateFrom') && (c.data.spec.replicateFrom !== null))

                    if(typeof cluster !== 'undefined') {
                        const promotedCluster = JSON.parse(JSON.stringify(cluster.data));
                        promotedCluster.spec.replicateFrom = null;

                        store.commit('loading', true);

                        sgApi
                        .update('sgclusters', promotedCluster)
                        .then( (response) => {
                            vc.notify('Cluster "' + promotedCluster.metadata.name + '" promoted successfully');
                            vc.fetchAPI('sgclusters');
                            store.commit('loading', false);
                        })
                        .catch(function(err) {
                            console.log(err);
                            vc.checkAuthError(err);
                            vc.notify('Cluster "' + promotedCluster.metadata.name + '" could not be promoted');
                            store.commit('loading', false);
                        });
                    }
                }
            }
        }
	}

</script>

<style scoped>

    ul.breadcrumbs {
        margin-top: 0;
    }

    .component {
        width: 20px;
        height: 20px;
        display: inline-block;
        margin-right: 10px;
        margin-top: 2px;
        background-repeat: no-repeat !important;
        background-size: contain;
    }

    .component.sgcluster {
        background-image: url();
        transform: scale(.8) translateY(-3px);
    }

    .component.sgshardedcluster {
        background-image: url();
        transform: scale(.8) translateY(-3px);
    }

    .component.sgstream {
        background-image: url();
        transform: scale(.8) translateY(-3px);
    }

    .component.sginstanceprofile {
        background-image: url();
        transform: scale(.8) translateY(-3px);
    }

    .component.sgpgconfig {
        background-image: url();
    }

    .component.sgpoolconfig {
        background-image: url();
    }

    .component.sgdistributedlog {
        background-image: url();
        transform: translateY(-2px);
    }

    .component.sgbackup {
        background-image: url();
        transform: scale(.8);
        margin-top: -3px;
    }

    .component.sgdbop {
        background-image: url();
        transform: scale(.8) translateY(-3px);
    }

    .component.sgobjectstorage {
        background-image: url()
    }

    .component.sgscript {
        background-image: url()
    }

    .component.application {
        background-image: url();
    }

    .component.sgconfig {
        background-image: url("");
    }

    .component.user, .component.role, .component.clusterrole {
        background-image: url("");
    }

</style>